%*******************************************************************************
%*
%*   Copyright ©2009 Alexandru Marin
%*
%*   This file is part of nwave/pMRI C library.
%*
%*   This project started as an MSc degree project during a
%*   stage at the Paris-Est university, under joint supervision of prof.
%*   Bogdan Ionescu (Image Analysis and Processing Laboratory, "Politehica"
%*   University of Bucharest), Caroline Chaux and Jean-Christophe Pesquet
%*   (Laboratoire d'Informatique, Université Paris-Est, Institut Gaspard Monge).
%*
%*   nwave/pMRI C libray is free software: you can redistribute it and/or modify
%*   it under the terms of the GNU General Public License as published by
%*   the Free Software Foundation, either version 2 of the License, or
%*   (at your option) any later version.
%*
%*   nwave/pMRI C libray is distributed in the hope that it will be useful,
%*   but WITHOUT ANY WARRANTY; without even the implied warranty of
%*   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
%*   GNU General Public License for more details.
%*
%*   You should have received a copy of the GNU General Public License
%*   along with nwave/pMRI C library. If not, see <http://www.gnu.org/licenses/>
%*
%*******************************************************************************


%
%
% function mri_write_matrix(filename, mat[, prec])
%
% Writes matrix mat in file named filename using csv (comma separated
% values) with the following format:
% - first value is an integer representing the number of
%   dimensions of mat, ndim
% - next ndim values represent the sizes of the matrix along
%   each dimension
% - following values are the actual matrix data
% You can oveerride the default precision by speecifying the optional 
% parameter prec
%
function mri_write_matrix(filename, mat, prec)

if ~exist('filename', 'var')
   help mri_write_matrix
   error('You muse provide a filename!');
end

if ~exist('mat', 'var')
   help mri_write
   error('You muse provide a matrix to  write!');
end

matdims = ndims(mat);
matsize = size(mat);

% Swap first two dimensions
matsize = [matsize(2) matsize(1) matsize(3:end)];

% Handle the case of simple vectors
if(matdims == 2 && any(matsize==1))
    matdims = 1;
    matsize = prod(matsize);
end



% Just putting the matrix in row-wise fashion and writing it to file
if(~exist('prec', 'var'))
    csvwrite(filename, [double(matdims) double(matsize) double(reshape(permute(mat,[2,1,3:ndims(mat)]), 1, prod(matsize)))]);
else
    dlmwrite(...
        filename,...
        [double(matdims) double(matsize) double(reshape(permute(mat,[2,1,3:ndims(mat)]), 1, prod(matsize)))],...
        'delimiter', ',', 'precision', prec);
end

end